package com.woniuxy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.entity.*;
import com.woniuxy.entity.dto.WithdrawalDTO;
import com.woniuxy.mapper.DrugMapper;
import com.woniuxy.mapper.DrugPatientMapper;
import com.woniuxy.mapper.ReturnMoneyMapper;
import com.woniuxy.mapper.WithdrawalMapper;
import com.woniuxy.service.SaasService;
import com.woniuxy.service.WithdrawalService;
import com.woniuxy.util.PageParam;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.ResponseEnum;
import com.woniuxy.util.SnowflakeIdGenerator;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@Service
public class WithdrawalServiceImpl implements WithdrawalService , SaasService {

    @Resource
    private WithdrawalMapper withdrawalMapper;

    @Resource
    private DrugPatientMapper drugPatientMapper;

    @Resource
    private ReturnMoneyMapper returnMoneyMapper;

    @Resource
    private DrugMapper drugMapper;

    @Override
    public ResponseData<?> queryList(PageParam<Withdrawal> pageParam) {
        PageHelper.startPage(pageParam.getPageNum(),pageParam.getPageSize());
        List<Withdrawal> withdrawalList = withdrawalMapper.queryList(pageParam.getParam());
        return new ResponseData<>().ok(new PageInfo<>(withdrawalList));
    }

    //异步 todo
    @SneakyThrows
    @Override
    public ResponseData<?> addWithdrawal(WithdrawalDTO withdrawalDTO) {
        if (withdrawalDTO.getDocId()==null
                || withdrawalDTO.getCaseId()==null
                || withdrawalDTO.getDrugDetails()==null
                || withdrawalDTO.getDrugDetails().isEmpty()
                || withdrawalDTO.getContent()==null
                || withdrawalDTO.getContent().isEmpty()) {
            return new ResponseData<>().fail(ResponseEnum.EMPTY);
        }
        //雪花id
        SnowflakeIdGenerator snow = new SnowflakeIdGenerator();
        long nextId = snow.nextId();
        Withdrawal withdrawal = new Withdrawal();
        withdrawal.setDwNo(String.valueOf(nextId));
        withdrawal.setDwCaseId(withdrawalDTO.getCaseId());//设置病人id
        withdrawal.setDwWorkerId(withdrawalDTO.getDocId());//设置医生id
        withdrawal.setDwCause(withdrawalDTO.getContent());//设置退药原因
        //添加到退药申请表
        withdrawalMapper.addWithdrawal(withdrawal);

        List<DrugDetail> drugDetails = withdrawalDTO.getDrugDetails();
        List<DrugReturnDetail> drugReturnDetails = new ArrayList<>();
        for (DrugDetail drugDetail : drugDetails) {
            DrugReturnDetail drugReturnDetail = new DrugReturnDetail();
            drugReturnDetail.setWdDrugStoreId(drugDetail.getMdDrugstoreId());
            drugReturnDetail.setWdWithdrawalId(String.valueOf(nextId));
            drugReturnDetail.setWdBuyPrice(drugDetail.getMdBuyPrice());//开药时价格
            drugReturnDetail.setWdNum(drugDetail.getMdNum());//退药数量
            drugReturnDetail.setWdName(drugDetail.getMdName());//药品名
            drugReturnDetails.add(drugReturnDetail);
        }
        //添加到退药明细
        withdrawalMapper.addBatchDrugReturnDetails(drugReturnDetails);
        return new ResponseData<>().ok();
    }

    //根据退药申请dwNo查询退药明细
    @Override
    public ResponseData<?> queryDrugReturnDetail(String dwNO) {
        List<DrugReturnDetail> drugReturnDetailList = withdrawalMapper.queryDrugReturnDetail(dwNO);
        return new ResponseData<>().ok(drugReturnDetailList);
    }

    //根据退药申请表id修改退药申请表状态
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseData<?> updateWithdrawal(Integer id) {
        //校验数据是否正确
        Withdrawal withdrawal = withdrawalMapper.queryWithdrawalById(id);

        //如果这个订单存在 执行
        if (withdrawal!=null){

            //查询当前病人的账号余额
            Withdrawal withdrawalPause = drugPatientMapper.queryByPurse(withdrawal.getDwCaseId());
            //查询当前病人退药详情
            List<DrugReturnDetail> drugReturnDetailList = withdrawalMapper.queryDrugReturnDetail(withdrawal.getDwNo());
            List<Integer> ids = new ArrayList<>();
            //计算出退药金额
            BigDecimal price = new BigDecimal(0);
            for (DrugReturnDetail drugReturnDetail: drugReturnDetailList){
                BigDecimal multiply = drugReturnDetail.getWdBuyPrice().multiply(BigDecimal.valueOf(drugReturnDetail.getWdNum()));
                ids.add(drugReturnDetail.getWdDrugStoreId());
                price = price.add(multiply);
            }


            //查询原本药品的数量
            List<Drug> drugList = drugMapper.queryByIds(ids);
            for (Drug drug:drugList){
                for (DrugReturnDetail drugReturnDetail:drugReturnDetailList){
                    if (drug.getId().equals(drugReturnDetail.getWdDrugStoreId())){
                        drug.setDsStock(String.valueOf(Integer.parseInt(drug.getDsStock())+drugReturnDetail.getWdNum()));
                    }
                }
            }
            //修改库存
            drugMapper.updateBatchStock(drugList);

            //生成退款明细表 把退药订单编号、金额、病人id输入进去
            ReturnMoney returnMoney = new ReturnMoney();
            returnMoney.setBrNo(withdrawal.getDwNo());
            returnMoney.setBrMoney(price);
            returnMoney.setBrCaseId(withdrawal.getDwCaseId());
            //退药成功之后 把退还的金额加到病人的账户上
            price = withdrawalPause.getPurse().add(price);
            withdrawalPause.setDwCaseId(withdrawal.getDwCaseId());
            withdrawalPause.setPurse(price);
            //把金额退回
            drugPatientMapper.update(withdrawalPause);
            //插入退款明细表
            returnMoneyMapper.addDrug(returnMoney);
            //修改退药表的状态为已完成
            withdrawal.setDwStatus("1");
            withdrawalMapper.updateWithdrawal(withdrawal);

            return new ResponseData<>().ok();
        } else {
            return new ResponseData<>().fail(ResponseEnum.EMPTY);
        }


    }
}
